package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"github.com/valyala/fasthttp"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	basepath = kingpin.Flag("path", "base path").Default(".").String()
	port     = kingpin.Flag("port", "port to listen").Default("10101").Short('p').String()
)

func main() {
	kingpin.Parse()
	logfile := PrepareLog()
	srv := Initialize()
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan)
	go func() {
		a := <-signalChan
		log.Printf("[Info] Receive signal %v\n", a)
		Finalize(&srv, logfile)
		os.Exit(0)
	}()
	fasthttp.ListenAndServe(":"+*port, srv.Handle)
}

func Initialize() (srv Server) {
	p, err := NewProducer()
	if err != nil {
        log.Println(err)
        os.Exit(2)
    }
    srv = Server{producer: p}
	return
}

func Finalize(srv *Server, file *os.File) {
	var err	error
	if srv != nil {
		if err= srv.producer.Close(); err!=nil {
			log.Printf("[Info] Close producer error: %v\n", err)
		} else {
			srv = nil
			log.Printf("[Info] Close producer\n")
		}
	}
	if file != nil {
		if err = file.Close(); err != nil {
			log.Panicf("[Error] Close log file error: %v.", err)
		} else {
			file = nil
		}
	}
	if err != nil {
		input := 0
		fmt.Println("\nFail to execute Finalize operation.")
		fmt.Print("To try Finalize operation again, press '1'. To exit forcibly, press '2'.(1/2): ")
		fmt.Scanf("%d", &input)
		if input == 2 {
			return
		} else {
			Finalize(srv, file)
		}
	}
}
